package com.waypolice.manager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.common.utils.StringUtil;
import com.waypolice.manager.service.BorRegisterService;
import com.waypolice.mapper.*;
import com.waypolice.mapper.handwriting.CmsBorAuditingMapperSon;
import com.waypolice.mapper.handwriting.CmsBorRegisterExtMapper;
import com.waypolice.pojo.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 描述:
 *
 * @author zyp
 * @description 借阅登记service实现类
 * @create 2019-03-12 14:53
 */
@Service
public class BorRegisterServiceImpl implements BorRegisterService {

    private static final Logger logger = LoggerFactory.getLogger(BorRegisterServiceImpl.class);

    @Autowired
    private CmsBorRegisterExtMapper cmsBorRegisterExtMapper;

    @Autowired
    private CmsBorRegisterMapper cmsBorRegisterMapper;

    @Autowired
    private CmsBorAuditingMapperSon cmsBorAuditingMapperSon;

    @Autowired
    private CmsBorAuditingMapper cmsBorAuditingMapper;

    @Autowired
    private CmsBorRegFileMapper cmsBorRegFileMapper;

    @Autowired
    private CmsJudVolumeMapper cmsJudVolumeMapper;

    @Autowired
    private CmsJudItemMapper cmsJudItemMapper;

    @Autowired
    private CmsSinItemMapper cmsSinItemMapper;

    @Override
    public Map<String, Object> getRegisterList(Integer offset, Integer limit,String search, String sort, String order, String fileType) {
        Map<String, Object> result = new HashedMap();
        PageHelper.offsetPage(offset,limit);
        if(StringUtils.isBlank(search)){
            search = null;
        }
        Map<String,String> searchMap = new HashMap<>();
        searchMap.put("search",search);
        List<Map<String,String>> registerList = cmsBorRegisterExtMapper.getRegisterList(searchMap);
        registerList = resetRegistList(registerList);
        int count = cmsBorRegisterExtMapper.countRegisterList(searchMap);
        result.put("rows", registerList);
        result.put("total", count);
        return result;

    }

    /**
     * @author:zyp
     * @description 插入数据之后的同时，查询id
     * @date: 2019/3/12 14:54
     * @return 
     */
    @Override
    public long insertSelectId(CmsBorRegister cmsBorRegister) {
        cmsBorRegisterExtMapper.insertSelectId(cmsBorRegister);
        return cmsBorRegister.getId();
    }

    /**
     * @author:zyp
     * @description 根据主键更新数据
     * @date: 2019/3/12 15:54
     * @return 
     */
    @Override
    public void updateByPrimaryKeySelective(CmsBorRegister cmsBorRegister) {
        cmsBorRegisterMapper.updateByPrimaryKeySelective(cmsBorRegister);
    }

    /**
     * @author:zyp
     * @description 根据主键更新数据
     * @date: 2019/3/25 15:51
     * @return 
     */
    @Override
    public void updateByPrimaryKey(CmsBorRegister cmsBorRegister) {
        cmsBorRegisterMapper.updateByPrimaryKey(cmsBorRegister);
    }

    /**
     * @author:zyp
     * @description 先将线下借阅的未在指定时间求取的文档置为已失效
     * @date: 2019/3/12 16:10
     * @return 
     */
    @Override
    public void updateBorStatusTo2() {
        List<CmsBorRegister> cmsBorRegisters=cmsBorRegisterExtMapper.selectBorStatus0To2();
        //目前已经过期的登记表id的列表
        List<Long> lists = new ArrayList<Long>();
        for(CmsBorRegister cmsBorRegister : cmsBorRegisters){
            lists.add(cmsBorRegister.getId());
            //将该文件的状态置为未借阅
            //暂时储存到其中 fileType 文件形式：卷/件
            String fileType = cmsBorRegister.getFileType();
            //暂时储存到其中 fileId 文件形式：卷/件 id
            Long fileId = cmsBorRegister.getBorUserId();
            updateFileState(MathUtils.object2Int(fileType),fileId);
        }
        if(lists!=null&&lists.size()>0){
            //将登记表的字段修改为已失效
            cmsBorRegisterExtMapper.updateBorStatus0To2(lists);
        }
    }

    /**
     * @author:zyp
     * @description 修改检索已经过期的内容为已过期
     * @date: 2019/5/31 10:26
     * @return 
     */
    @Override
    public void updateSearchStatusTo3() {
        cmsBorRegisterExtMapper.updateSearchStatusTo3();
    }

    /**
     * @author:zyp
     * @description 借阅记录的审核信息数据
     * @date: 2019/3/12 17:36
     * @return 
     */
    @Override
    public Map<String, Object> getApprovalInfo(Integer offset, Integer limit, String sort, String order, Long id) {
        Map<String, Object> result=new HashedMap();
        CmsBorAuditingExample example=new CmsBorAuditingExample();
        CmsBorAuditingExample.Criteria criteria = example.createCriteria();
        criteria.andBorRegisterIdEqualTo(id);
        int i =cmsBorAuditingMapper.countByExample(example) ;
        PageHelper.offsetPage(offset, limit, false);
        List<Object> approvalInfo = cmsBorAuditingMapperSon.getApprovalInfo(id);
        result.put("rows", approvalInfo);
        result.put("total", i);
        return result;
    }

    /**
     * @author:zyp
     * @description 将借阅登录id 、借阅文件id、文件形式插入到登记 文件关联表中
     * @date: 2019/3/18 17:30
     * @return 
     */
    @Override
    public void insertBorrowRegFile(long cmsBorRegisterId, String borrowFileId, String fileShape) {
        CmsBorRegFile cmsBorRegFile = new CmsBorRegFile();
        cmsBorRegFile.setBorRegId(cmsBorRegisterId);
        cmsBorRegFile.setFileId(MathUtils.string2long(borrowFileId));
        cmsBorRegFile.setFileShape(fileShape);
        cmsBorRegFileMapper.insertSelective(cmsBorRegFile);
    }

    /**
     * @author:zyp
     * @description 获取线下的借阅归还列表
     * @date: 2019/3/20 18:26
     * @return 
     */
    @Override
    public Map<String, Object> getBorrowReturnList(Integer offset, Integer limit, String sort, String order, String fileType) {
        PageHelper.offsetPage(offset,limit);
        List<Map<String, String>> result = cmsBorRegisterExtMapper.getBorrowReturnList();
        result = resetRegistList(result);
        //获取借阅归还的列表数量
        int count = cmsBorRegisterExtMapper.getCountBorReturnList();
        Map<String, Object> map = new HashMap<>(2);
        map.put("rows",result);
        map.put("total",count);
        return map;
    }

    /**
     * @author:zyp
     * @description 根据登记主键ID获取借阅（检索）文件ID
     * @date: 2019/3/21 10:23
     * @return 
     */
    @Override
    public List<CmsBorRegFile> selectBorRgtistById(Long id) {
        CmsBorRegFileExample cmsBorRegFileExample = new CmsBorRegFileExample();
        cmsBorRegFileExample.or().andBorRegIdEqualTo(id);
        List<CmsBorRegFile> cmsBorRegFiles = cmsBorRegFileMapper.selectByExample(cmsBorRegFileExample);
        return cmsBorRegFiles;
    }

    /**
     * @author:zyp
     * @description 根据登记Id获取登记表数据
     * @date: 2019/3/25 14:45
     * @return 
     */
    @Override
    public CmsBorRegister getRegistById(Long id) {
        CmsBorRegister cmsBorRegister = cmsBorRegisterMapper.selectByPrimaryKey(id);
        return cmsBorRegister;
    }
    
    /**
     * @author:zyp
     * @description 根据任务类型查出当天的登记数量
     * @date: 2019/3/25 15:01
     * @return 
     */
    @Override
    public int countByTaskType(long taskType, String data) {
        Map<String,Object> parameterMap = new HashedMap();
        parameterMap.put("taskType",taskType);
        parameterMap.put("data",data);
        int count = cmsBorRegisterExtMapper.countByTaskType(parameterMap);
        return count;
    }

    /**
     * @author:zyp
     * @description 检索登记数据
     * @date: 2019/3/29 9:11
     * @return 
     */
    @Override
    public Object getSearchRegister(int offset,int limit,String sort,String order) {
        PageHelper.offsetPage(offset,limit);
        List<CmsBorRegister> searchRegister = cmsBorRegisterExtMapper.getSearchRegister();
        int count = cmsBorRegisterExtMapper.countSearchRegister();
        Map<String,Object> result = new HashMap<>();
        result.put("rows",searchRegister);
        result.put("total",count);
        return result;
    }

    /**
     * @author:zyp
     * @description 授权检索登记
     * @date: 2019/3/29 11:16
     * @return 
     */
    @Override
    public Object accreditSearchRegiser(String fileIds, String registerIds) {
        String[] registerId = registerIds.split(",");
        Map fileIdMap = JSONObject.parseObject(fileIds,Map.class);
        //将此登记表中的文件类型---文书 审计 默认为选中的第一个文件类型为准
        Long fileId = 0L;
        int fileShape = -1;
        boolean isFirst= true;
        for(String id : registerId){
            Set<Map.Entry<Object,Object>> entrySet = fileIdMap.entrySet();
            for(Map.Entry<Object,Object> entry : entrySet){
                CmsBorRegFile cmsBorRegFile = new CmsBorRegFile();
                cmsBorRegFile.setBorRegId(MathUtils.string2long(id));
                cmsBorRegFile.setFileId(MathUtils.object2Long(entry.getKey()));
                cmsBorRegFile.setFileShape(String.valueOf(entry.getValue()));
                cmsBorRegFileMapper.insertSelective(cmsBorRegFile);
                if(isFirst){
                    fileId = MathUtils.object2Long(entry.getKey());
                    fileShape = MathUtils.object2Int(entry.getValue());
                    isFirst = false;
                }
            }
            CmsBorRegister cmsBorRegister = new CmsBorRegister();
            cmsBorRegister.setId(MathUtils.string2long(id));
            CmsJudVolume cmsJudVolume = null;
            String volClass = null;
            switch (fileShape){
                //如果是卷
                case (int)BorrowConstant.BORROW_FILE_VOLUM:
                    cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(fileId);
                    volClass = cmsJudVolume.getVolClass();
                    cmsBorRegister.setFileType(volClass);
                    break;
                case (int)BorrowConstant.BORROW_FILE_ITEM:
                    CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(fileId);
                    cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(cmsJudItem.getItmeVolId());
                    volClass = cmsJudVolume.getVolClass();
                    cmsBorRegister.setFileType(volClass);
                    break;
                case (int)BorrowConstant.BORROW_FILE_SIN_ITEM:
                    CmsSinItem cmsSinItem = cmsSinItemMapper.selectByPrimaryKey(fileId);
                    volClass = cmsSinItem.getItemExp1();
                    cmsBorRegister.setFileType(volClass);
                    break;
                    default:
            }
            cmsBorRegister.setBorStatus(1);
            cmsBorRegisterMapper.updateByPrimaryKeySelective(cmsBorRegister);
        }
        return new CmsResult(1,"success",null);
    }

    /**
     * @author:zyp
     * @description 生成登记策略号
     * @date: 2019/4/18 9:10
     * @return 
     */
    @Override
    public String producePolicyNum(CmsBorRegister cmsBorRegister) {
        //登记号的生成策略2018051400001  日期+当前的流程类型+当前已借阅的个数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String data = sdf.format(new Date());
        long borType = cmsBorRegister.getTaskType();
        int count = countByTaskType(borType,data);
        count++;
        String countStr = (String) StringUtil.completionDigit(count,4);
        //最终的登记号
        String finalRegist = data+borType+countStr;
        return finalRegist;
    }

    /**
     * @author:zyp
     * @description 获取审核成功列表
     * @date: 2019/4/24 14:02
     * @return 
     */
    @Override
    public List<CmsBorRegister> selectAuditSuccessList(int userId) {
        CmsBorRegisterExample cmsBorRegisterExample = new CmsBorRegisterExample();
        CmsBorRegisterExample.Criteria criteria = cmsBorRegisterExample.createCriteria();
        criteria.andBorUserIdEqualTo((long)userId);
        criteria.andExtend2EqualTo("1");
        criteria.andBorStatusEqualTo(1);
        criteria.andPlanReturnTimeGreaterThan(new Date());
        List<CmsBorRegister> cmsBorRegisters = cmsBorRegisterMapper.selectByExample(cmsBorRegisterExample);
        return cmsBorRegisters;
    }

    /**
     * @author:zyp
     * @description 获取我的检索结果数据
     * @date: 2019/6/17 10:04
     * @return 
     */
    @Override
    public Object mySearchData(int offset,int limit,String sort,String order) {
        PageHelper.offsetPage(offset,limit);
        CmsBorRegisterExample cmsBorRegisterExample = new CmsBorRegisterExample();
        CmsBorRegisterExample.Criteria criteria = cmsBorRegisterExample.createCriteria();
        criteria.andTaskTypeEqualTo(3);
        criteria.andExtend2EqualTo("1");
        List<Integer> borStatusList = new ArrayList();
        borStatusList.add(0);
        borStatusList.add(2);
        criteria.andBorStatusIn(borStatusList);
        List<CmsBorRegister> cmsBorRegisters = cmsBorRegisterMapper.selectByExample(cmsBorRegisterExample);
        int count = cmsBorRegisterMapper.countByExample(cmsBorRegisterExample);
        Map<String,Object> result = new HashMap<>();
        result.put("rows",cmsBorRegisters);
        result.put("total",count);
        return result;
    }

    /**
     * @author:zyp
     * @description 获取即将到期以及已经到期的数据列表
     * @date: 2019/4/24 14:26
     * @return 
     */
    @Override
    public List<CmsBorRegister> selectExpireList(int userId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String expireStr = DateTimeUtil.getNextDay(format.format(new Date()),"3");
        Date expireDate = DateTimeUtil.strToDate(expireStr);
        CmsBorRegisterExample cmsBorRegisterExample = new CmsBorRegisterExample();
        CmsBorRegisterExample.Criteria criteria = cmsBorRegisterExample.createCriteria();
        criteria.andBorUserIdEqualTo((long)userId);
        criteria.andExtend2EqualTo("1");
        criteria.andBorStatusEqualTo(1);
        criteria.andPlanReturnTimeLessThan(expireDate);
        List<CmsBorRegister> cmsBorRegisters = cmsBorRegisterMapper.selectByExample(cmsBorRegisterExample);
        return cmsBorRegisters;
    }

    /**
     * @author:zyp
     * @description 将文件修改为未借阅
     * @date: 2019/3/19 11:52
     * @return 
     */
    private void updateFileState(int fileType , long fileId){
        //如果当前文件 是卷 则根据卷id进行修改
        if(fileType== BorrowConstant.BORROW_FILE_VOLUM){
            CmsJudVolume cmsJudVolume = new CmsJudVolume();
            cmsJudVolume.setVolId(fileId);
            cmsJudVolume.setVolStatus(BorrowConstant.BORROW_STATUS_NOBOR);
            cmsJudVolumeMapper.updateByPrimaryKeySelective(cmsJudVolume);
        }else{
            CmsJudItem cmsJudItem = new CmsJudItem();
            cmsJudItem.setItemId(fileId);
            cmsJudItem.setItemStatus((long)BorrowConstant.BORROW_STATUS_NOBOR);
            cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
        }
    }

    /**
     * @author:zyp
     * @description 重置登录列表(因借阅可以多个件一起借阅 故借阅)
     * @date: 2019/3/19 14:32
     * @return
     */
    public List<Map<String,String>> resetRegistList(List<Map<String,String>> registerList){
        Map<String,Map<String,String>> registIdMap = new HashMap<>();
        List<Map<String,String>> finalRegisterList = new ArrayList<>();
        for (Map<String,String> register : registerList){
            String registId = String.valueOf(register.get("REGISTID"));
            if(registIdMap.containsKey(registId)){
                Map<String,String> oldMap = registIdMap.get(registId);
                int index = finalRegisterList.indexOf(oldMap);
                oldMap.put("TITLE",oldMap.get("TITLE")+"--"+register.get("TITLE"));
                oldMap.put("FILEID",String.valueOf(oldMap.get("FILEID"))+","+String.valueOf(register.get("FILEID")));
                finalRegisterList.set(index,oldMap);
            }else{
                registIdMap.put(registId,register);
                finalRegisterList.add(register);
            }
        }
        return finalRegisterList;
    }

}